package com.demo.nfcdemo.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.demo.nfcdemo.R;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ljb
 * @des
 * @date 2020/5/23
 */
public class NdefListAdapter extends RecyclerView.Adapter<NdefListAdapter.ViewHolder> {

    private final LayoutInflater mInflater;
    private List<String[][]> mData = new ArrayList<>();

    public NdefListAdapter(Context c) {
        mInflater = LayoutInflater.from(c);
    }

    public void setData(List<String[][]> data) {
        mData.clear();
        mData.addAll(data);
        notifyDataSetChanged();
    }

    public void addData(List<String[][]> data) {
        mData.addAll(data);
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View root = mInflater.inflate(R.layout.rv_item_ndef_list, parent, false);
        return new ViewHolder(root);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        String[][] texts = mData.get(position);
        StringBuilder sb = new StringBuilder();
        for (String[] text : texts) {
            for (String s : text) {
                sb.append(s);
                sb.append("\n");
            }
        }
        holder.tvNdefContent.setText(sb.toString());

        holder.itemView.setOnClickListener(v -> {
            if (onItemClickListener!=null){
                onItemClickListener.onItemClick(texts,position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {

        private final TextView tvNdefContent;

        ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvNdefContent = itemView.findViewById(R.id.tv_ndef_content);
        }
    }

    private OnItemClickListener onItemClickListener;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }
    public interface OnItemClickListener {
        void onItemClick(String[][] texts, int position);
    }
}
